import re

from django.contrib.auth.backends import ModelBackend

from users.models import User


class MyAuthenticateBackend(ModelBackend):
    def authenticate(self, request, username=None,
                     password=None, **kwargs):
        try:
            if re.match(r'^1[3-9]\d{9}$',username):
                user = User.objects.get(mobile=username)

            elif re.match(r'^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$',username):
                user = User.objects.get(email=username)
            else:
                user = User.objects.get(username=username)

        except User.DoesNotExist:
            return None
        if user.check_password(password):

            return user